package com.woniu.rabbitMq.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniu.common.util.SendMessageUtil;
import com.woniu.rabbitMq.entity.FailMessage;
import com.woniu.rabbitMq.mapper.FailMessageMapper;
import com.woniu.rabbitMq.service.FailMessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author Administrator
* @description 针对表【t_fail_message】的数据库操作Service实现
* @createDate 2024-05-19 16:59:30
*/
@Service
@Slf4j
public class FailMessageServiceImpl extends ServiceImpl<FailMessageMapper, FailMessage>
    implements FailMessageService{

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 定时器执行
     */
    @Override
    public void sendMsg() {
        // 一般情况不用把所有消息全部拿出来，而是一次性拿出多少条，这里是拿出不为1的消息，0初始1成功2失败
        List<FailMessage> list = lambdaQuery().ne(FailMessage::getState, 1).list();

        // 把消息发给mq
        list.forEach(financeMessage -> {
            Integer count = financeMessage.getCount();
            String message = financeMessage.getMessage();
            String exchange = financeMessage.getExchange();
            String routingKey = financeMessage.getRoutingKey();

            // 指定次数退出
            if (count > 10) {
                log.error("count:{}, message:{}, exchange:{}, routingKey:{}", count, message, exchange, routingKey);
                return;
            }

            // 重发
            SendMessageUtil.sendMsg(redisTemplate, rabbitTemplate, exchange, routingKey, message, financeMessage.getId().toString());

            // 重发完，默认发成功
            financeMessage.setState(1);
            updateById(financeMessage);
        });
    }
}




